package com.baosight.risk.web.xtzy;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baosight.risk.api.xtaa.sequences.IXtaaSequencesService;
import com.baosight.risk.api.xtzy.IXtzyRoleUserService;
import com.baosight.risk.api.xtzy.IXtzyUserService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.service.constant.Constant;
import com.baosight.risk.service.system.entity.SysRole;
import com.baosight.risk.service.xtzy.bo.XtzyRoleUserReplaceBO;
import com.baosight.risk.service.xtzy.entity.XtzyRoleUser;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.xtzy.vo.XtzyCompanyVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 类 名: XtzyRoleUserController
 * 作 者: 黎秋荣
 * 创 建：2019年05月22日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Slf4j
@RestController
@RequestMapping("/xtzy/roleuser")
@Api(value = "组织人员角色授权", description = "组织人员角色授权", produces = MediaType.APPLICATION_JSON)
public class XtzyRoleUserController extends BaseController {

    @Autowired
    private IXtzyRoleUserService roleUserService;
    @Autowired
    private IXtzyUserService userService;
    @Autowired
    private IXtaaSequencesService sequencesService;
    
    /**
     * 根据组织ID获取用户和所属角色
     *
     * @param compId
     * @return
     */
    @GetMapping("queryUserRole")
    @ApiOperation("根据组织ID获取用户和所属角色")
    public AjaxResult queryUserRole(String compId, HttpServletRequest request) {
        String userDesc = request.getParameter("userDesc");
        String userCode = request.getParameter("userCode");
        return success(roleUserService.queryUserRole(compId, userDesc, userCode));
    }


    @GetMapping("queryAppointUserRole")
    @ApiOperation("根据组织ID获取指定角色的用户")
    public AjaxResult queryAppointUserRole(String compId, HttpServletRequest request) {
        String userDesc = request.getParameter("userDesc");
        String userCode = request.getParameter("userCode");
        return success(roleUserService.queryAppointUserRole(compId, userDesc, userCode));
    }




    @ApiOperation("根据组织ID及用户ID获取用户所属角色")
    @RequestMapping(value = "getUserRoles", method = RequestMethod.GET)
    public AjaxResult getUserRoles(String compId, String userId) {
        if (StringUtils.isEmpty(compId) || StringUtils.isEmpty(userId)) {
            return error("组织/用户信息不能为空");
        }
        List<SysRole> list = roleUserService.getUserRoles(compId, userId);
        return success(list);
    }

    /**
     * 保存组织用户授权关系
     *
     * @param companyVO
     * @return
     */
    @PostMapping("saveCompUser")
    @Log(title = "保存组织用户授权关系")
    @ApiOperation("保存组织用户授权关系")
    public AjaxResult saveCompUser(@RequestBody XtzyCompanyVO companyVO) {
        if (StringUtils.isEmpty(companyVO.getCompCode()) ||
                CollectionUtils.isEmpty(companyVO.getUserList())) {
            return error("数据有误！");
        }
        log.info("保存组织用户授权关系参数：" + companyVO.toString());
        return toAjax(roleUserService.saveCompUser(companyVO));
    }
    
    /**
     * 保存HR用户授权关系
     *
     * @param companyVO
     * @return
     */
    @PostMapping("saveHrCompUser")
    @Log(title = "保存HR用户授权关系")
    @ApiOperation("保存HR用户授权关系")
    public AjaxResult saveHrCompUser(@RequestBody XtzyCompanyVO companyVO)  throws Exception{
    	List<XtzyUser> userList = companyVO.getUserList();
        if (StringUtils.isEmpty(companyVO.getCompCode()) ||
                CollectionUtils.isEmpty(userList)) {
            return error("数据有误！");
        }
        List<XtzyUser> rest = new ArrayList<XtzyUser>();
        for(XtzyUser user : userList){
        	XtzyUser us = userService.selectByName(user.getUserCode());
        	if(us==null){
        		user = (XtzyUser) BeanUtils.initBean(user);
        		user.setUserType(Constant.USER_TYPE.FORMAL);
        		user.setStatus("10");
        		userService.insertUser(user);
        		userService.addUserToIplat(user);
        		rest.add(user);

        	}else{
                //禁用时未添加人员数据
        	    if("20".equals(us.getStatus())){
                    userService.addUserToIplat(user);
                }

        		us.setStatus("10");
        		userService.update(us);
                rest.add(us);
        	}
        }
        companyVO.setUserList(rest);
        log.info("保存组织用户授权关系参数：" + companyVO.toString());
        return toAjax(roleUserService.saveCompUser(companyVO));
    }
    
    /**
     * 保存临时用户授权关系
     *
     * @param companyVO
     * @return
     */
    @PostMapping("saveTempCompUser")
    @Log(title = "保存临时用户授权关系")
    @ApiOperation("保存临时用户授权关系")
    public AjaxResult saveTempCompUser(@RequestBody XtzyCompanyVO companyVO)  throws Exception{
    	List<XtzyUser> userList = companyVO.getUserList();
        if (StringUtils.isEmpty(companyVO.getCompCode()) ||
                CollectionUtils.isEmpty(userList)) {
            return error("数据有误！");
        }
        List<XtzyUser> rest = new ArrayList<XtzyUser>();
        for(XtzyUser user : userList){
        	XtzyUser us = userService.selectByUserType(user.getPhoneCode(),Constant.USER_TYPE.TEMP);
        	if(us==null){
        		user = (XtzyUser) BeanUtils.initBean(user);
        		user.setUserType(Constant.USER_TYPE.TEMP);
        		user.setStatus("10");
        		userService.insertUser(user);
        		userService.addUserToIplat(user);
        		rest.add(user);
        	}else{
                if("20".equals(us.getStatus())){
                    userService.addUserToIplat(user);
                }
        		us.setStatus("10");
        		userService.update(us);
        	}
        }
        companyVO.setUserList(rest);
        log.info("保存组织用户授权关系参数：" + companyVO.toString());
        return toAjax(roleUserService.saveCompUser(companyVO));
    }
    
    /**
     * 替换组织用户授权关系
     *
     * @param companyVO
     * @return
     */
    @PostMapping("replaceCompUser")
    @Log(title = "替换组织用户授权关系")
    @ApiOperation("替换组织用户授权关系")
    public AjaxResult replaceCompUser(@RequestBody XtzyRoleUserReplaceBO replaceBO){
    	try {
			roleUserService.replace(replaceBO);
		} catch (Exception e) {
			return error(e.getMessage());
		}
        return success();
    }
    
    @PostMapping("genUserCode")
    @Log(title = "生成userCode")
    @ApiOperation("生成userCode")
    public AjaxResult genUserCode(){
        String userCode = sequencesService.generateCodeById("", "gozyUser.userCode", "", "", "");
        return success("生成成功！", userCode);
    }

    /**
     * 删除组织用户授权关系
     *
     * @param id
     * @return
     */
    @GetMapping("deleteCompUser")
    @Log(title = "删除组织用户授权关系", businessType = BusinessType.DELETE)
    @ApiOperation("删除组织用户授权关系")
    public AjaxResult deleteCompUser(String id) {
        log.info("删除组织用户授权关系参数：" + id);
        return toAjax(roleUserService.deleteCompUser(id));
    }

    /**
     * 保存用户角色授权关系
     * 需要传入参数：company、compUserList、roleList
     *
     * @param companyVO
     * @return
     */
    @PostMapping("saveUserRole")
    @Log(title = "保存用户角色授权关系")
    @ApiOperation("保存用户角色授权关系==参数：company、compUserList、roleList")
    public AjaxResult saveUserRole(@RequestBody XtzyCompanyVO companyVO) {
        if (StringUtils.isEmpty(companyVO.getUserList()) ||
                StringUtils.isEmpty(companyVO.getRoleList())) {
            return error("数据有误！");
        }
        log.info("保存用户角色授权关系参数：" + companyVO.toString());
        try {
			return success(roleUserService.saveUserRole(companyVO));
		} catch (Exception e) {
			return error(e.getMessage());
		}
    }

    /**
     * 获取用户及其所在组织
     */
    @GetMapping("userComp")
    @ApiOperation("获取用户及其所在组织")
    public AjaxResult getUserComp(
            @RequestParam(value = "userCode", required = false) String userCode,
            @RequestParam(value = "userDesc", required = false) String userDesc,
            @RequestParam(value = "ext1", required = false) String ext1,
            @RequestParam(value = "deptCode", required = false) String deptCode,
            @RequestParam(value = "compCode", required = false) String compCode
    ) {
        startPage();
        XtzyRoleUser user = new XtzyRoleUser();
        user.setUserCode(userCode);
        user.setUserDesc(userDesc);
        user.setExt1(ext1);
        user.setExt2(deptCode);
        user.setExt3(compCode);
        return getResultPage(roleUserService.selectByUserCode(user));
    }

}
